package com.lbh.scheduler;

import java.util.HashMap;
import java.util.Map;
/**
 * @param注意 当外包的方法是 public static 修饰时，可以用以下方法直接调用到方法
 */
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

import com.lbh.job.OneJob;
/**
 * 简单的调度器
 * @author leimo
 *
 */
public class OneScheduler {
	public static OneScheduler one = new OneScheduler();

	public static void main(String[] args) {
		Map<Object, Object> map = one.getScheduler("job1", "group1", "trigger1", 5, OneJob.class);
		JobDetail job = (JobDetail) map.get("job");
		SimpleTrigger trigger = (SimpleTrigger) map.get("trigger");
		Scheduler scheduler = (Scheduler) map.get("scheduler");
		one.schedulerStart(scheduler, job, trigger);
		try {
			Thread.sleep(6000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		one.schedulerEnd(scheduler);
	}

	/**
	 * 创建调度器
	 * 
	 * @param jobName
	 * @param groupName
	 * @param triggerName
	 * @param time
	 * @param cla
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<Object, Object> getScheduler(String jobName, String groupName, String triggerName, int time, Class cla) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
			JobDetail job = newJob(cla).withIdentity(jobName, groupName).build();
			SimpleTrigger trigger = newTrigger()//
					.withIdentity(triggerName, groupName)//
					.startNow()//
					.withSchedule(//
							SimpleScheduleBuilder//
									.simpleSchedule()//
									.withIntervalInSeconds(time)//
									.repeatForever())
					.build();
			map.put("job", job);
			map.put("trigger", trigger);
			map.put("scheduler", scheduler);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 开启
	 * 
	 * @param scheduler
	 * @param job
	 * @param trigger
	 */
	public void schedulerStart(Scheduler scheduler, JobDetail job, SimpleTrigger trigger) {
		try {
			scheduler.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭
	 * 
	 * @param scheduler
	 */
	public void schedulerEnd(Scheduler scheduler) {
		try {
			scheduler.shutdown();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
